import gobject

from fvutil.managers import objectmanager
from fvutil import fvcon

class Timeline(objectmanager.ObjectManager):
    
    def __init__(self, my_id):
        objectmanager.ObjectManager.__init__(self, fvcon.ALL, my_id)
        
    def __get_messages(self, begin, end):
        c = self._table._conn
	created_times = c.execute(''' SELECT created FROM objects''')
	for ct in created_times:
		created = ct['created'] 
		print 'created',created
		print 'created > begin?',(created>begin)
		print 'created < end?',(created<end)

        msgs = c.execute(''' SELECT * FROM objects WHERE created > ? AND created < ? ''', (begin, end))
        return msgs
    
    def get_messages(self, flash, begin, end):
        msgs = self.__get_messages(begin, end)
        result = {}
        result['command'] = fvcon.ACK_GET_MESSAGES
        result['messages'] = msgs
        print 'Getting messages',msgs
        flash.sendResult(self, result)



        """
        result = {}
        result['command'] = uicon.ACK_GET_MESSAGES
        result['messages'] = []
        # TODO: Message need to be sent in chronological order
        result['messages'].append({'id':34, 'src_id':57, 'src_name':"Aidan", 'reply_id':-1, 'tags':"Business, Urgent",
                                   'text':"Visitor from BoA", 'msg_type': uicon.PICMSG})
        result['messages'].append({'id':45, 'src_id':55, 'src_name':"Bob", 'reply_id':34, 'tags':"Business, Letter",
                                   'text':"Demo is ready", 'msg_type': uicon.TXTMSG})
        result['messages'].append({'id':46, 'src_id':56, 'src_name':"Teresa", 'reply_id':34, 'tags':"Picnic, Letter",
                                   'text':"Debuggin in the lake", 'msg_type': uicon.AUDIOMSG})
        """
        
    def get_message_count(self, flash, begin, end):
        msgs = self.__get_messages(begin, end)
        result = {}
        
        result['command'] = fvcon.ACK_GET_MESSAGE_COUNT
        result['begin'] = begin
        result['end'] = end
        
        msg_by_type = {}
        for msg in msgs:
            type = msg['type']
            if type not in msg_by_type:
                msg_by_type[type] = 0
            msg_by_type[type] += 1
        
        ui_ordered = []
        for (type, count) in msg_by_type.iteritems():
            ui_ordered.append({'msg_type' : type, 'count':count})
        
        result['messages'] = ui_ordered
        flash.sendResult(self, result)
    